//
//  TPVerticalPageContainerView.m
//  ThePaperBase
//
//  Created by liubo on 2021/8/20.
//  Copyright © 2021 scar1900. All rights reserved.
//

#import "LBVerticalPageContainerView.h"
#import "LBVerticalPageViewCell.h"

@interface LBVerticalPageContainerView () <UIScrollViewDelegate>

@property (nonatomic, strong) NSMutableDictionary *viewClsDict; //注册 view 的字典，key为view的类名，value 为identifier
@property (nonatomic, strong) NSMutableArray *reuseViews; //重用view的实例对象数组

/// 竖直滚动的外层容器scrollView
@property (nonatomic, strong) UIScrollView *contentScrollView;

///上面的视图
@property (nonatomic, strong) LBVerticalPageViewCell *topView;
///中间的视图
@property (nonatomic, strong) LBVerticalPageViewCell *middleView;
/// 下面的视图
@property (nonatomic, strong) LBVerticalPageViewCell *bottomView;

@property (nonatomic, assign) NSInteger currentIndex;

@end

@implementation LBVerticalPageContainerView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self addSubview:self.contentScrollView];
    }
    return self;
}

- (void)registerClass:(nonnull Class)cellClass forViewReuseIdentifier:(NSString *)identifier
{
    [self.viewClsDict setObject:NSStringFromClass(cellClass) forKey:identifier];
}

- (__kindof LBVerticalPageViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier
{
    for (LBVerticalPageViewCell *cell in self.reuseViews)
    {
        if ([cell.reuseIdentifier isEqualToString:identifier]) {
            return cell;
        }
    }
    
    Class cellCls = NSClassFromString(self.viewClsDict[identifier]);
    LBVerticalPageViewCell *cell = [[cellCls alloc] initWithReuseIdentifier:identifier];
    __weak typeof(self) weakSelf = self;
    cell.next = ^{
        [weakSelf gotoNext];
    };
    cell.toLast = ^{
        [weakSelf pullToLast];
    };
    return cell;
}

#pragma mark - public

- (void)gotoNext
{
    NSInteger count = 0;
    if (self.dataSource &&
        [self.dataSource respondsToSelector:@selector(numberOfViewForVerticalPageContainerView:)]) {
        count = [self.dataSource numberOfViewForVerticalPageContainerView:self];
    }
    if (self.currentIndex >= count - 1) {
        return;
    }
    self.currentIndex ++;
    self.currentIndex = MIN(count - 1, self.currentIndex);
    [UIView animateWithDuration:0.5 animations:^{
        [self.contentScrollView setContentOffset:CGPointMake(0, CGRectGetHeight(self.bounds) * 2)];
    } completion:^(BOOL finished) {
        [self reloadAfterTranslation];
    }];
}

- (void)pullToLast
{
    self.currentIndex --;
    self.currentIndex = MAX(0, self.currentIndex);
      
    /// 翻到下一页之前，需要将下一页偏移量设置为0
    [self.bottomView configContentOffset:0];
    [UIView animateWithDuration:0.5 animations:^{
        [self.contentScrollView setContentOffset:CGPointMake(0, 0)];
    } completion:^(BOOL finished) {
        [self reloadAfterTranslation];
    }];
}

- (void)reloadData
{
    self.contentScrollView.contentOffset = CGPointMake(0, CGRectGetHeight(self.bounds));
    [self reloadTopView];
    [self reloadMiddleView];
    [self reloadBottomView];
}

#pragma mark - private
- (void)reloadAfterTranslation
{
    NSInteger count = [self.dataSource numberOfViewForVerticalPageContainerView:self];
    if (self.currentIndex < count) {
        ///需要先刷新中间视图，这样保证我们返回到中间的时候，和上一个状态无缝贴合
        [self reloadMiddleView];
   }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.contentScrollView setContentOffset:CGPointMake(0, CGRectGetHeight(self.bounds))];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self.currentIndex - 1 >= 0 && count > self.currentIndex - 1) {
                [self reloadTopView];
            }
            
            if (self.currentIndex + 1 < count) {
                [self reloadBottomView];
            }

            if (self.delegate &&
                [self.delegate respondsToSelector:@selector(moveBackMiddleAfterTranslation:)]) {
                [self.delegate moveBackMiddleAfterTranslation:self];
            }
        });
     });
}

- (void)reloadTopView
{
    [self.topView removeFromSuperview];
    [self.reuseViews addObject:self.topView];
    NSInteger count = [self.dataSource numberOfViewForVerticalPageContainerView:self];
    NSInteger index =  MAX(0, self.currentIndex - 1);
    if (index >= count) {
        return;
    }
    LBVerticalPageViewCell *cell = [self.dataSource verticalPageView:self viewAtIndex:index];
    cell.frame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
    [self.contentScrollView addSubview:cell];
    self.topView = cell;
    [self.reuseViews removeObject:self.topView];
    
}

- (void)reloadMiddleView
{
    [self.middleView removeFromSuperview];
    [self.reuseViews addObject:self.middleView];
    NSInteger count = [self.dataSource numberOfViewForVerticalPageContainerView:self];
    if (self.currentIndex >= count) {
        return;
    }
    LBVerticalPageViewCell *cell = [self.dataSource verticalPageView:self viewAtIndex:self.currentIndex];
    cell.frame = CGRectMake(0, CGRectGetHeight(self.bounds), CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
    [self.contentScrollView addSubview:cell];
    self.middleView = cell;
    [self.reuseViews removeObject:self.middleView];
}

- (void)reloadBottomView
{
    [self.bottomView removeFromSuperview];
    [self.reuseViews addObject:self.bottomView];
    NSInteger count = [self.dataSource numberOfViewForVerticalPageContainerView:self];
    if (self.currentIndex + 1 >= count) {
        return;
    }
    LBVerticalPageViewCell *cell = [self.dataSource verticalPageView:self viewAtIndex:MIN(self.currentIndex + 1, count - 1)];
    cell.frame = CGRectMake(0, CGRectGetHeight(self.bounds) * 2, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
    [self.contentScrollView addSubview:cell];
    self.bottomView = cell;
    [self.reuseViews removeObject:self.bottomView];
}

#pragma mark - lazy load

- (UIScrollView *)contentScrollView
{
    if (!_contentScrollView) {
        _contentScrollView = [[UIScrollView alloc] init];
        _contentScrollView.frame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
        _contentScrollView.contentSize = CGSizeMake(CGRectGetWidth(self.bounds), 3 * CGRectGetHeight(self.bounds));
        _contentScrollView.delegate = self;
        _contentScrollView.scrollEnabled = NO;
    }
    return _contentScrollView;
}

- (NSMutableDictionary *)viewClsDict
{
    if (!_viewClsDict) {
        _viewClsDict = [[NSMutableDictionary alloc] init];
    }
    return _viewClsDict;
}

@end
